#include "WW_RLE_Zero.h"

using namespace std;

bool WW_RLE_Zero::Decode(const uint8_t *src, uint8_t *des, size_t srcLength, size_t desLength)
{
    size_t desIndex = 0;
    for (int i = 0; i < srcLength; ++i)
    {
        if(src[i] == 0)
        {
            auto count = i + 1 < srcLength ? src[i + 1] : 1;
            while (count-- > 0)
            {
                des[desIndex] = 0;
                desIndex++;
                if(desIndex >= desLength)
                    return false;
            }
            i++;
        }
        else
        {
            des[desIndex] = src[i];
            desIndex++;
            if(desIndex >= desLength)
                return false;
        }
    }
    if(desIndex >= desLength)
        return false;
    return true;
}

bool WW_RLE_Zero::Encode(const uint8_t *src, size_t srcLength, vector<uint8_t> &des)
{
    vector<uint8_t> r;
    r.reserve(srcLength);
    for (int i = 0; i < srcLength;)
    {
        if(src[i] == 0)
        {
            uint8_t count = 1;
            while(true)
            {
                if(i + count >= srcLength)
                    break;
                if(src[i + count] != 0)
                    break;
                if(count == 255)
                    break;
                count++;
            }
            r.emplace_back(0);
            r.emplace_back(count);
            i += count;
        }
        else
        {
            r.emplace_back(src[i]);
            i++;
        }
    }
    r.swap(des);
    return true;
}
